package com.java.demo.sync;

import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.atomic.AtomicInteger;

public class SynchronizedAndLock implements Runnable{
    private int seats = 100000;

    private AtomicInteger atomicSeats = new AtomicInteger(100000);

//    private ReentrantLock lock = new ReentrantLock();  // 默认非公平锁
    private ReentrantLock lock = new ReentrantLock(true);  // 使用公平锁

    /**
     * 非公平锁
     */
    synchronized private void decreaseSync() {
        if (seats > 0) {
            seats -= 1;
        }
        System.out.println(Thread.currentThread().getName() + ", seats=" + seats);
    }

    private void decreaseLock() {
        try {
            lock.lock();
            if (seats > 0) {
                seats -= 1;
            }
            System.out.println(Thread.currentThread().getName() + ", seats=" + seats);
        } finally {
            lock.unlock();
        }
    }

    private void decreaseAtomic() {
        System.out.println(Thread.currentThread().getName() + ", seats=" + atomicSeats.decrementAndGet());
        seats = atomicSeats.get();
    }

    @Override
    public void run() {
        while (true) {
//            decreaseSync(); // 1200ms
//            decreaseLock(); // 1850ms
            decreaseAtomic(); // 1270ms
            if (seats == 0) {
                break;
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        SynchronizedAndLock main = new SynchronizedAndLock();
        Thread t1 = new Thread(main, "A");
        Thread t2 = new Thread(main, "B");
        t1.start();
        t2.start();
        long start = System.currentTimeMillis();
        t1.join();
        t2.join();
        System.out.println("total time=" + (System.currentTimeMillis() - start));
    }
}
